package protectjava;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import utils.JDBCUtilsRun;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.List;

/*
访问数据库
下面的实例演示了如何使用 Servlet 访问 RUNOOB 数据库。
 */
@WebServlet(name = "DatabaseAccess")
public class DatabaseAccess extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
//    连接到数据库
    QueryRunner queryRunnery = new QueryRunner(JDBCUtilsRun.getDataSource());
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //         设置响应内容类型
        response.setContentType("text/html:charset=UTF-8");
        PrintWriter out = response.getWriter();
        String title = "servlet mysql 测试";
        String doctype = "<!DOCTYPE html>\n";
        out.print(doctype +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n"+
                "</body>\n</html>");


        String sql = "SELECT id,name,url FROM websites";
        try {
            List<Object[]> result = queryRunnery.query(sql,new ArrayListHandler());
            System.out.println(result.getClass());
            for (Object[] objs : result){
//            遍历对象数组
                for (Object obj : objs){
                    System.out.print(obj);
                }
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
